import 'package:flutter_admin/models/user_info.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/base_team_odoo_api.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/base_team.dart';
import 'package:flutter_admin/pages/odoo/base_team/base_team_dialog.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:flutter_admin/utils/utils.dart';

import 'base_teampath/team_path_select.dart';
import 'base_teamuser/station_user_select.dart';
import 'configure_postratio/configure_postratio_list.dart';

class BaseTeamList extends StatefulWidget {
  BaseTeamList({Key? key}) : super(key: key);

  @override
  _BaseTeamListState createState() => _BaseTeamListState();
}

class _BaseTeamListState extends State<BaseTeamList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  BaseTeam baseTeam = BaseTeam();
  List<BaseTeam> selectedList = [];
  //车间
  List<SelectOptionVO> workshopIdList = [];
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
      _loadSelectVO();
    });
  }

  _loadSelectVO() async {
    UserInfo userInfo = StoreUtil.getCurrentUserInfo();
    if (userInfo.major != null) {
      workshopIdList = await DynamicDataApi.getModelSelect(
          model: "hr.department",
          name: "complete_name",
          key: "parent_id",
          operator: "!=",
          val: null);
    } else {
      baseTeam.workshopId = userInfo.deptId;
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    UserInfo userInfo = StoreUtil.getCurrentUserInfo();
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          userInfo.major != null
              ? CrySelect(
                  width: 280,
                  label: '车间',
                  dataList: workshopIdList,
                  value: baseTeam.workshopId,
                  onSaved: (v) => {baseTeam.workshopId = v},
                )
              : CryInput(
                  width: 200,
                  label: '生产车间',
                  enable: false,
                  value: userInfo.deptName,
                ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('车间')),
        DataColumn(label: Text('班组编码')),
        DataColumn(label: Text('班组名称')),
        DataColumn(label: Text('备注')),
      ],
      getCells: (m) {
        BaseTeam baseTeam = BaseTeam.fromMap(m);
        return [
          DataCell(Text(baseTeam.workshopName ?? '--')),
          DataCell(Text(baseTeam.teamcode ?? '--')),
          DataCell(Text(baseTeam.teamname ?? '--')),
          DataCell(Text(baseTeam.remark ?? '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
        CryButton(
            label: '人员配置',
            iconData: Icons.code,
            onPressed: selectedList.length == 1
                ? () => _selectUser(selectedList[0])
                : null),
        CryButton(
            label: '工序配置',
            iconData: Icons.code,
            onPressed: selectedList.length == 1
                ? () => _selectPath(selectedList[0])
                : null),
        CryButton(
            label: '配置系数岗位',
            iconData: Icons.code,
            onPressed: selectedList.length == 1
                ? () => _coefficient(selectedList[0])
                : null)
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          Wrap(
            children: [
              isDisplayDesktop(context) ? form : Container(),
              Padding(
                padding: EdgeInsets.only(top: 24),
                child: isDisplayDesktop(context) ? buttonBar : Container(),
              )
            ],
          ),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _selectUser(BaseTeam? baseTeam) {
    Utils.fullscreenDialog(TeamUserSelect(
      baseTeam: baseTeam,
    ));
  }

  _selectPath(BaseTeam? baseTeam) {
    Utils.fullscreenDialog(TeamPathSelect(
      baseTeam: baseTeam,
    ));
  }

  _coefficient(BaseTeam? baseTeam) {
    showDialog(
      barrierDismissible: false,
      context: context,
      builder: (BuildContext context) => Dialog(
        child: ConfigurePostratioList(
          baseTeam: baseTeam,
        ),
      ),
    ).then((v) {
      if (v != null) {
        if(baseTeam == null){
          // 新增时回到第一页
          tableKey.currentState?.pageTo(0);
        }
        _loadData();
        // _subscription = eventChannel.receiveBroadcastStream().listen(_onEnvent,onError: _onError);
      }
    });
    // Utils.fullscreenDialog(ConfigurePostratioList(
    //   baseProductionstation: baseProductionstation,
    // ));
  }

  _reset() {
    baseTeam = BaseTeam();
    formKey.currentState!.reset();
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi = await BaseTeamOdooApi.page(
        data: {"page": page, "domainList": baseTeam.toDomainList()});
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: BaseTeamDialog(),
      ),
    ).then((v) {
      if (v != null) {
        baseTeam = v;
        _query();
      }
    });
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<BaseTeam>((e) => BaseTeam.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        } else if (v == OperationType.add) {
          _selectUser(selectedList[0]);
        } else if (v == OperationType.edit) {
          _selectPath(selectedList[0]);
        } else if (v == OperationType.delete) {
          _coefficient(selectedList[0]);
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.add,
          enabled: selectedList.length == 1,
          child: ListTile(
            leading: const Icon(Icons.code),
            enabled: selectedList.length == 1,
            title: Text('人员配置'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.edit,
          enabled: selectedList.length == 1,
          child: ListTile(
            leading: const Icon(Icons.code),
            enabled: selectedList.length == 1,
            title: Text('工序配置'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.delete,
          enabled: selectedList.length == 1,
          child: ListTile(
            leading: const Icon(Icons.code),
            enabled: selectedList.length == 1,
            title: Text('配置系数岗位'),
          ),
        ),
      ],
    );
  }
}
